import pygame
import os

class AudioPlayer:
    def __init__(self):
        pygame.mixer.init()
        self.current_song = None
        self.beep_sound = pygame.mixer.Sound('beep.wav')  # 蜂鸣声文件
        self.is_playing_song = False  # 新增标志位跟踪歌曲播放状态
    
    def load_song(self, song_path):
        """加载选中的歌曲"""
        if os.path.exists(song_path):
            self.current_song = song_path
            try:
                pygame.mixer.music.load(self.current_song)
                return True
            except Exception as e:
                print(f"加载歌曲失败: {e}")
                return False
        return False
    
    def play(self):
        """播放当前选中的歌曲"""
        if self.current_song:
            try:
                # 先停止任何正在播放的声音
                self.stop()
                pygame.mixer.music.play()
                self.is_playing_song = True  # 设置歌曲播放标志
            except Exception as e:
                print(f"播放歌曲失败: {e}")
                self.is_playing_song = False
                # 只有在歌曲播放失败时才播放蜂鸣声
                self.beep_sound.play()
        else:
            # 没有选中歌曲时播放蜂鸣声
            self.beep_sound.play()
    
    def stop(self):
        """停止播放"""
        pygame.mixer.music.stop()
        self.is_playing_song = False